package com.temi.iot.jwt;

import com.alibaba.fastjson.JSON;
import com.temi.iot.jwt.model.TokenValue;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.time.Instant;
import java.util.Base64;
import java.util.UUID;

@Component
public class JwtUtil {

    /**
     * 由字符串生成加密key
     */
    private SecretKey generalKey() {
        String stringKey = "shop密鑰:->f4841accf24sd43dd";
        byte[] encodedKey = Base64.getEncoder().encode(stringKey.getBytes());
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }

    /**
     * 创建jwt
     */
    public String createJWT(String subject) throws Exception {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey key = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setPayload(subject)
                .signWith(signatureAlgorithm, key);
        return builder.compact();
    }

    /**
     * 解密jwt
     */
    public Claims parseJWT(String jwt) {
        SecretKey key = generalKey();
        return Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwt).getBody();
    }

    /**
     * 生成subject信息
     */
    public static String generalSubject(TokenValue tokenValue) {
        tokenValue.setRan(UUID.randomUUID().toString().replaceAll("-", ""));
        tokenValue.setCte(Instant.now());
        return JSON.toJSONString(tokenValue);
    }

}
